package com.xiaoyu.lanling.feature.chat.model.message

import `in`.srain.cube.request.JsonData
import android.graphics.Color
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.im.datamodel.AppMessage
import com.xiaoyu.im.datamodel.MessagePayload.IMessageAction
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.feature.chat.viewholder.ChatViewHolderManager

class ChatMessageSystemItem(message: AppMessage) : ChatMessageBaseItem(message) {

    companion object {
        fun parseBackgroundColor(backgroundColor: String): Int {
            return if (backgroundColor.isEmpty()) {
                AppContext.getColor(R.color.chat_message_admin_background)
            } else try {
                Color.parseColor(backgroundColor)
            } catch (e: Throwable) {
                AppContext.getColor(R.color.chat_message_admin_background)
            }
        }

        fun parseTextColor(colorString: String): Int {
            return if (colorString.isEmpty()) {
                AppContext.getColor(R.color.colorWhite)
            } else try {
                Color.parseColor(colorString)
            } catch (e: Throwable) {
                AppContext.getColor(R.color.colorWhite)
            }
        }

        fun parseLastContentTextColor(colorString: String): Int {
            return if (colorString.isEmpty()) {
                AppContext.getColor(R.color.colorSecondaryText)
            } else try {
                Color.parseColor(colorString)
            } catch (e: Throwable) {
                AppContext.getColor(R.color.colorSecondaryText)
            }
        }
    }

    val prefixIcon: String
    val text: String
    val textColor: Int
    val backgroundColor: Int
    val url: String
    val action: IMessageAction

    init {
        val attrs: JsonData = message.payload.attrsCopy
        val textColor: String = attrs.optString("textColor")
        val backgroundColor: String = attrs.optString("backgroundColor")

        prefixIcon = attrs.optString("prefixIcon")
        text = message.payload.text
        url = message.payload.url
        this.textColor = parseTextColor(textColor)
        this.backgroundColor = parseBackgroundColor(backgroundColor)
        action = message.payload.actionWrapper.action
    }

    override fun getViewType(): Int {
        return ChatViewHolderManager.TYPE_SYSTEM
    }
}